package sun.cn.common.builder;

import java.lang.reflect.Proxy;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.collections.CollectionUtils;

import com.google.common.collect.Lists;
import sun.cn.common.cacheDto.proxy.ServiceProxy;
import sun.cn.common.cacheDto.proxy.handler.ProxyHandler;
import sun.cn.common.utils.StringExtendUtils;

/**
 * bean代理工厂类
 * 
 * @author sunlingao
 * @title
 * @date 2017年7月6日
 * @version
 */
class BeanFactory {

	private static final String PROXY_KEY = "%s_%s";

	private static ConcurrentHashMap<String, Object> proxyContainer = new ConcurrentHashMap<>();

	private BeanFactory() {
	}

	/**
	 * 根据代理类生成实例
	 * 
	 * @author sunlingao
	 * @date 2017年7月6日
	 * @version
	 * @param input
	 * @param impl
	 * @param proxy
	 * @return
	 */
	public static <T> T getBean(Object input,Class<?> intface,Class<T> impl, ServiceProxy proxy) {
		return getBean(input,intface, impl, Lists.newArrayList(proxy));
	}
	
	@SuppressWarnings("unchecked")
	public static <T> T getBean(Object input,Class<?> intface,Class<T> impl, List<ServiceProxy> proxies){
		String key = String.format(PROXY_KEY, StringExtendUtils.getClassName(intface.getName()), buildProxyName(proxies));
		if (proxyContainer.get(key) != null)
			return (T) proxyContainer.get(key);
		ProxyHandler proxyCls = new ProxyHandler(input, proxies);
		T obj = (T) Proxy.newProxyInstance(impl.getClassLoader(), new Class[] { intface }, proxyCls);
		if (obj != null)
			proxyContainer.put(key, obj);
		return obj;
	}
	
	/**
	 * 
	 * @author sunlingao@zbj.com
	 * @date 2017年8月8日
	 * @version
	 * @param proxies
	 * @return
	 */
	private static String buildProxyName(List<ServiceProxy> proxies){
		StringBuilder sb = new StringBuilder();
		if(CollectionUtils.isNotEmpty(proxies)){
			for(ServiceProxy proxy : proxies){
				sb.append(proxy.getProxyName()).append("_");
			}
		}
		if(sb.length() > 0)
			sb = sb.delete(sb.length()-1, sb.length());
		return sb.toString();
	}

}
